package com.yxc.plan.wolf.service.impl;

import com.yxc.plan.wolf.common.ServerResponse;
import com.yxc.plan.wolf.domain.Comment;
import com.yxc.plan.wolf.domain.Tweet;
import com.yxc.plan.wolf.domain.User;
import com.yxc.plan.wolf.domain.po.AddCommentPO;
import com.yxc.plan.wolf.domain.repository.CommentRepository;
import com.yxc.plan.wolf.domain.repository.TweetRepository;
import com.yxc.plan.wolf.domain.repository.UserRepository;
import com.yxc.plan.wolf.service.interfaces.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
* @Description : 
* @Author      : abc@vanke.com
* @Date        : 2018-12-17 19:28
*/
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TweetRepository tweetRepository;

    @Override
    public ServerResponse add(AddCommentPO addCommentPO) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(addCommentPO, comment);
        comment = commentRepository.save(comment);

        // 更新评论数
        Tweet tweet = tweetRepository.findByDeletedAndId(false, addCommentPO.getTweetId());
        int count = tweet.getCommentCount().intValue()+1;
        tweet.setCommentCount(new Long(count));
        tweetRepository.save(tweet);

        if (comment.getId() > 0 ) {
            return ServerResponse.createBySuccessMessage("评论成功");
        } else {
            return ServerResponse.createByErrorMessage("评论失败");
        }
    }

    @Override
    public ServerResponse<List<Comment>> list(Long tweetId, Pageable pageable) {
        Page<Comment> commentPage = commentRepository.findByDeletedAndTweetId(false, tweetId, pageable);
        List<Comment> commentList = commentPage.getContent();
        List<Long> userIds = new ArrayList<>();
        for (Comment comment: commentList) {
            userIds.add(comment.getUserId());
        }

        List<User> userList = userRepository.findByDeletedAndIdIn(false, userIds);
        HashMap<Long, User> userHashMap = new HashMap<>();
        for (User user: userList) {
            userHashMap.put(user.getId(), user);
        }

        for (Comment comment: commentList) {
            User user = userHashMap.get(comment.getUserId());
            comment.setUser(user);
        }

        return ServerResponse.createBySuccess("访问成功", commentList);
    }
}
